# -*- coding: UTF-8 -*-
import platform
import os
import hashlib


def file_hash(file_path: str, hash_method) -> str:
    if not os.path.isfile(file_path):
        print('file not exist。')
        return ''
    h = hash_method()
    with open(file_path, 'rb') as f:
        while True:
            b = f.read(8192)
            if not b:
                break
            h.update(b)
    return h.hexdigest()


def isWondows():
    '''
    判断当前运行平台
    :return:
    '''
    sysstr = platform.system()
    if (sysstr == "Windows"):
        return True
    elif (sysstr == "Linux"):
        return False
    else:
        print("Other System ")
    return False


def doContext(isw):
    if isw:
        moonfile_path = "C:\\ProgramData\\ZeroTier\\One\\moons.d\\000000d48e83ed6d.moon"
        restart_cmd = "net stop ZeroTierOneService && net start ZeroTierOneService"
    else:
        moonfile_path = "/var/lib/zerotier-one/moons.d/000000d48e83ed6d.moon"
        restart_cmd = "systemctl restart zerotier-one"

    curHash = file_hash(moonfile_path, hashlib.md5)
    hashfile = "hash.txt"

    with open(hashfile, 'r') as f:
        oldhash = f.read()
        f.close()
    print(oldhash)
    print(curHash)
    if oldhash != curHash:
        os.system(restart_cmd)
        with open(hashfile, 'w') as f:
            f.write(curHash)
            f.close()
    else:
        print("nothing changed")
    pass


if __name__ == '__main__':
    isW = isWondows()
    doContext(isW)
    pass
